/*
 * JBeagle - a Java toolkit for genetic algorithms.
 * 
 * Copyright (c) 2010 Matthijs Snel
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package jbeagle.core.ops;

import jbeagle.core.ConstraintViolatedException;
import jbeagle.core.ListIndividual;

public class RealMutator extends AbstractMutator<ListIndividual<Double>, Double> {

	public static final double	DEFAULT_MINRANGE = -0.2,
								DEFAULT_MAXRANGE = 0.2;
	
	private double minRange, maxRange;
	
	public RealMutator() {
		this( Mutator.DEFAULT_RATE, DEFAULT_MINRANGE, DEFAULT_MAXRANGE );
	}
	
	public RealMutator( double rate ) {
		this( rate, DEFAULT_MINRANGE, DEFAULT_MAXRANGE );
	}
	
	public RealMutator( double rate, double min, double max ) {
		super( rate );
		setMinRange(min);
		setMaxRange(max);
	}
	
	public double getMinRange() {
		return minRange;
	}

	public void setMinRange(double minRange) {
		this.minRange = minRange;
	}

	public double getMaxRange() {
		return maxRange;
	}

	public void setMaxRange(double maxRange) {
		this.maxRange = maxRange;
	}
	
	@Override
	public void apply( ListIndividual<Double> ind ) {
		double d;
		for ( int i = 0; i < ind.size(); i++ )
			if ( Math.random() < rate ) {
				d = minRange + Math.random() * (maxRange - minRange);
				try {
					ind.set( i, ind.get(i) + d);
				} catch (ConstraintViolatedException e) { //probably because out of bounds so reverse the add
					ind.set( i, ind.get(i) - d);
				}
			}
	}
}
